<template>
  <div class="app-container">
    <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        v-show="showSearch"
        label-width="80px"
    >
      <el-form-item label="用户名称" prop="customerName">
        <el-input
            v-model="queryParams.customerName"
            placeholder="请输入用户名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户电话" prop="customerPhone">
        <el-input
            v-model="queryParams.customerPhone"
            placeholder="请输入用户电话"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分配类型" prop="customerAuto">
        <el-select
            v-model="queryParams.customerAuto"
            placeholder="请选择分配类型"
            clearable
        >
          <el-option
              v-for="dict in dict.type.sys_fp"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="服务人员" prop="customerPlayer">
        <el-input
            v-model="queryParams.customerPlayer"
            placeholder="请输入服务人员"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工单状态" prop="customerFlag">
        <el-select
            v-model="queryParams.customerFlag"
            placeholder="请选择状态"
            clearable
        >
          <el-option
              v-for="dict in dict.type.sys_flag"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
        >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="primary"-->
<!--            plain-->
<!--            icon="Plus"-->
<!--            @click="handleAdd"-->
<!--            v-hasPermi="['web:CustomerRepair:add']"-->
<!--        >新增-->
<!--        </el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="success"-->
<!--            plain-->
<!--            icon="Edit"-->
<!--            :disabled="single"-->
<!--            @click="handleUpdate"-->
<!--            v-hasPermi="['web:CustomerRepair:edit']"-->
<!--        >修改-->
<!--        </el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="danger"-->
<!--            plain-->
<!--            icon="Delete"-->
<!--            :disabled="multiple"-->
<!--            @click="handleDelete"-->
<!--            v-hasPermi="['web:CustomerRepair:remove']"-->
<!--        >删除-->
<!--        </el-button>-->
<!--      </el-col>-->
      <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
        v-loading="loading"
        :data="CustomerRepairList"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="60" align="center" />
      <el-table-column
          label="用户ID"
          align="center"
          prop="customerId"
          v-if="false"
      />

<!--      展示表格-->
      <el-table-column width="180" label="工单编号" align="center" prop="customerKey" />
      <el-table-column width="120" label="服务类别" align="center" prop="customerHelp" />
      <el-table-column label="工单状态" align="center" prop="customerFlag">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_flag" :value="scope.row.customerFlag"/>
        </template>
      </el-table-column>
      <el-table-column width="120" label="接单时长" align="center" prop="createTime">
        <template slot-scope="scope">
          <span :style="{color: (scope.row.customerFlag == 0 || scope.row.customerFlag == 99) && getTimeOut(scope.row) == '超时' ? 'red' : ''}">{{ getTimeOut(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column width="120" label="联系电话" align="center" prop="customerPhone" />
      <el-table-column width="150" label="用户地址" align="center" prop="customerAddress" />
<!--      <el-table-column label="负责人" align="center" prop="customerPhone" />-->
      <el-table-column label="费用(元)" align="center" prop="quotationPrice" />
      <el-table-column width="150" sortable label="创建时间" align="center" prop="createTime" />
      <el-table-column width="150" label="接单人" align="center" prop="receiver" />
      <el-table-column width="200" label="维修人员" align="center" prop="proposer" />
      <el-table-column label="分配类型" align="center" prop="assignmentType">
        <template #default="scope">
          <dict-tag :options="dict.type.sys_fp" :value="scope.row.assignmentType" />
        </template>
      </el-table-column>

      <el-table-column
          fixed="right"
          label="操作"
          align="center"
          width="180"
      >
        <template slot-scope="scope">
          <router-link :to="'/gongdan/data/index/' + scope.row.customerKey" class="link-type">
            <span style="margin-right: 10px;color: #1890ff">详情</span>
          </router-link>
          <el-button
            v-if="(scope.row.customerFlag == 0 || scope.row.customerFlag == 99)"
            type="text"
            icon="Delete"
            @click="handleDisplay(scope.row)"
            v-hasPermi="['web:CustomerRepair:remove']"
          >调派
          </el-button>
          <el-button
              type="text"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['web:CustomerRepair:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />


    <!-- 添加或修改客户报修抢修对话框 -->
    <el-dialog title="预约工单" :visible.sync="open" width="700px" append-to-body>
      <el-form
        :inline="true"
        ref="CustomerRepairRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="分配类型" prop="customerAuto">
          <el-select v-model="form.customerAuto" placeholder="请选择分配类型">
            <el-option
              v-for="dict in dict.type.sys_fp"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务类型" prop="customerHelp">
          <el-select v-model="form.customerHelp" placeholder="请选择服务类型">
            <el-option label="客户报修抢修" value="客户报修抢修"></el-option>
            <el-option label="线路委托运维" value="线路委托运维"></el-option>
            <el-option label="充电桩运维" value="充电桩运维"></el-option>
            <el-option label="配电室运维" value="配电室运维"></el-option>
            <el-option label="电子化移交" value="电子化移交"></el-option>
            <el-option label="高低压业扩" value="高低压业扩"></el-option>
            <el-option label="带电作业服务" value="带电作业服务"></el-option>
            <el-option label="电气设备预试" value="电气设备预试"></el-option>
            <el-option label="配电设备销售" value="配电设备销售"></el-option>
            <el-option label="临电共享服务" value="临电共享服务"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户名称" prop="customerName">
          <el-input v-model="form.customerName" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="用户电话" prop="customerPhone">
          <el-input v-model="form.customerPhone" placeholder="请输入用户电话" />
        </el-form-item>
        <el-form-item label="用户地址" prop="customerAddress">
          <el-input
            v-model="form.customerAddress"
            placeholder="请输入用户地址"
          />
        </el-form-item>
        <el-form-item label="问题阐述" prop="customerMessage">
          <el-input
            v-model="form.customerMessage"
            type="textarea"
            placeholder="请输入问题阐述"
          />
        </el-form-item>
        <el-form-item label="预约时间" prop="customerTimer">
          <el-date-picker
            v-model="form.customerTimer"
            type="datetimerange"
            range-separator="至"
            start-placeholder="预约时间开始日期"
            end-placeholder="预约时间结束日期">
          </el-date-picker>
          <!--              <el-input v-model="form.customerTimer" placeholder="请输入选择日期" />-->
        </el-form-item>

        <el-form-item label="资料信息">
          <file-upload v-model="form.customerFiles" />
        </el-form-item>

        <el-form-item label="服务单位" prop="customerUnit">
          <el-select @change="changeUnit" v-model="form.customerUnit" placeholder="请选择服务单位">
            <el-option
              v-for="item in deptOptions"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptId">
            </el-option>
          </el-select>
<!--          <treeselect v-model="form.customerUnit" :options="deptOptions" :normalizer="normalizer" placeholder="请选择服务单位" />-->
<!--          <el-input v-model="form.customerUnit" placeholder="请选择服务单位" />-->
        </el-form-item>
        <el-form-item label="服务人员" prop="customerPlayer" v-if="form.customerAuto = '1'">
          <el-select multiple style="width:100%" v-model="form.customerPlayer" placeholder="请选择服务人员" :loading="bLoad">
            <el-option
              v-for="item in users"
              :key="item.userId"
              :label="`${item.nickName}【${item.userName}】`"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm"
          >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible" title="调派信息" width="500px" append-to-body>
      <el-form
        ref="displayRef"
        :model="dispatchForm"
        :rules="dispatchRules"
        label-width="80px"
      >
        <el-form-item label="单位" prop="companyId">
          <el-cascader
            ref="unit"
            style="width:100%"
            v-model="dispatchForm.companyId"
            placeholder="请选择单位"
            :options="frims"
            :props="{ checkStrictly: true }"
            @change="changeUnit"
            clearable></el-cascader>
        </el-form-item>
        <el-form-item label="人员" prop="customerPlayer">
          <el-select multiple style="width:100%" v-model="dispatchForm.customerPlayer" placeholder="请选择人员" :loading="bLoad">
            <el-option
              v-for="item in users"
              :key="item.userId"
              :label="`${item.nickName}【${item.userName}】`"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="调派说明" prop="dispatchExplain">
          <el-input
            v-model="dispatchForm.dispatchExplain"
            type="textarea"
            placeholder="请输入调派说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="btnLoading" type="primary" @click="onSubmitInfo"
          >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script type="text/javascript" name="CustomerRepair">
import moment from 'moment'
import {
  listCustomerRepair,
  getCustomerRepair,
  delCustomerRepair,
  addCustomerRepair,
  updateCustomerRepair, getAllDepts, FrimUser, designate
} from '@/api/web/CustomerRepair'
// import useUserStore from '@/store/modules/user'
import { getUserProfile } from '@/api/system/user'
import { listDept } from '@/api/system/dept'

export default {
  name: "Dispatch",
  components: {},
  dicts: ['sys_flag','sys_fp'],
  data() {
    return {
      deptOptions: [],
      activeName: 'first',
      order: {},
      dialogVisible: false,
      btnLoading: false,
      bLoad: false,
      frims: [],
      users: [],
      sys_fp: [],
      sys_flag: [],
      CustomerRepairList: [],
      open: false,
      buttonLoading: false,
      loading: true,
      showSearch: true,
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      title: '',
      form: {},
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerId: undefined,
        customerName: undefined,
        customerPhone: undefined,
        customerAddress: undefined,
        workOrderStatus: undefined,
        customerHelp: undefined,
        customerTimer: undefined,
        customerMessage: undefined,
        customerFiles: undefined,
        customerAuto: undefined,
        assignmentType: undefined,
        customerUnit: undefined,
        customerPlayer: undefined,
        customerFlag: undefined,
      },
      dispatchForm: {},
      dispatchRules: {
        customerPlayer: [
          { required: true, message: "人员ID不能为空", trigger: "change" },
        ],
        dispatchExplain: [
          { required: false },
        ],
        companyId: [
          { required: true, message: "单位ID不能为空", trigger: "blur" },
        ],
        customerKey: [{ required: true, message: "主键不能为空", trigger: "blur" }],
      },
      rules: {
        customerId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" },
        ],
        customerName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
        ],
        customerPhone: [
          { required: true, message: "用户电话不能为空", trigger: "blur" },
          { type: 'number', message: '用户电话必须为数字值'}
        ],
        customerAddress: [
          { required: true, message: "用户地址不能为空", trigger: "blur" },
        ],
        customerHelp: [
          { required: true, message: "维修类型不能为空", trigger: "blur" },
        ],
        customerTimer: [
          { required: true, message: "选择日期不能为空", trigger: "blur" },
        ],
        customerMessage: [
          { required: true, message: "问题阐述不能为空", trigger: "blur" },
        ],
        customerFiles: [
          { required: true, message: "资料信息不能为空", trigger: "blur" },
        ],
        customerAuto: [
          { required: true, message: "分配类型不能为空", trigger: "change" },
        ],
        customerUnit: [
          { required: true, message: "单位ID不能为空", trigger: "blur" },
        ],
        customerPlayer: [
          { required: true, message: "服务人员不能为空", trigger: "blur" },
        ],
        customerFlag: [
          { required: true, message: "状态不能为空", trigger: "change" },
        ],
        customerKey: [{ required: true, message: "主键不能为空", trigger: "blur" }],
      },
      serviceType: [{

      }]
    }
  },
  created() {
    this.getList();
  },
  watch: {
    dialogVisible(newValue) {
      if (newValue) {
        //getAllDepts-js路径
        getAllDepts({ parentId: 100 }).then(res => {
          // console.log(res, this.treeData(res.data), 'hhjhj')
          const arr = []
          res.data.forEach((item, index) => {
            if (item.parentId == 100) {
              res.data[index].label = item.deptName
              res.data[index].value = item.deptId
              arr.push(item)
            }
          })

          this.frims = arr
        })
      }
    },
    selectFrim(newValue) {
      if (newValue !== '' && newValue !== undefined && newValue != null) {
        this.bLoad = true
        FrimUser(this.selectFrim).then(res => {
          this.users = res.rows
          this.bLoad = false
        })
      }
    }
  },
  methods: {
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    // 工单是否超时
    getTimeOut(item) {
      // console.log(time)
      let info = '超时';
      if (item.customerFlag == 0 || item.customerFlag == 99) {
        const t1 = new Date()
        const t2 = new Date(moment(moment(item.createTime).add(15, 'minutes')))
        const times=t2.getTime()-t1.getTime();//时间差的毫秒数
        if (times > 0) {
          var days=parseInt(times/(24*1000*3600));//计算相差的天数
          var leave=times%(24*3600*1000);//计算天数后剩余的毫秒数

          var h=parseInt(leave/(3600*1000));//计算小时数

          //计算分钟数
          var h_leave=leave%(3600*1000);
          var min=parseInt(h_leave/(60*1000));

          //计算秒数
          var min_leave=h_leave%(60*1000);
          var sec=parseInt(min_leave/1000);
          if (days >0) {
            info = days + '天' + h + '小时' + min + '分' + sec + '秒'
          } else if (days == 0 && h > 0) {
            info = h + '小时' + min + '分' + sec + '秒'
          } else {
            info = min + '分' + sec + '秒'
          }
        } else {
          info = '超时'
        }
      } else {
        const diff = moment(moment(item.receiveTime)).diff(moment(item.createTime))
        var days=parseInt(diff/(24*1000*3600));//计算相差的天数
        var leave=diff%(24*3600*1000);//计算天数后剩余的毫秒数

        var h=parseInt(leave/(3600*1000));//计算小时数

        //计算分钟数
        var h_leave=leave%(3600*1000);
        var min=parseInt(h_leave/(60*1000));

        //计算秒数
        var min_leave=h_leave%(60*1000);
        var sec=parseInt(min_leave/1000);
        if (days >0) {
          info = days + '天' + h + '小时' + min + '分' + sec + '秒'
        } else if (days == 0 && h > 0) {
          info = h + '小时' + min + '分' + sec + '秒'
        } else {
          info = min + '分' + sec + '秒'
        }
      }
      return info
    },
    /** 查询客户报修抢修列表 */
    getList(query) {
      // console.log(this.queryParams)
      // console.log(query)
      this.loading = true;
      listCustomerRepair(this.queryParams).then((response) => {
        console.log(response, '111')
        this.CustomerRepairList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        customerId: null,
        customerName: null,
        customerPhone: null,
        customerAddress: null,
        customerHelp: null,
        customerTimer: null,
        customerMessage: null,
        customerFiles: null,
        customerAuto: null,
        customerUnit: null,
        customerPlayer: null,
        workOrderStatus: null,
        customerFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        customerKey: null,
      };
      this.resetForm("CustomerRepairRef");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryRef");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.customerKey);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      console.log('wwewe')
      this.reset();
      this.open = true;
      this.title = "添加客户报修抢修";
      listDept(this.queryParams).then(response => {
        console.log(response)
        this.deptOptions = response.data
        // this.deptList = this.handleTree(response.data, "deptId");
        // this.loading = false;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const customerKey = row.customerKey || ids;
      getCustomerRepair(customerKey).then((response) => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改客户报修抢修";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["CustomerRepairRef"].validate((valid) => {
        console.log(this.form)
        if (valid) {
          if (this.form.customerAuto == '2') {
            this.form.customerPlayer = this.form.customerPlayer.join(',')
          }
          this.buttonLoading = true;
          if (this.form.customerKey != null) {
            updateCustomerRepair(this.form)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addCustomerRepair(form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      console.log(row, '数据项')
      let that = this
      const customerKeys = row.customerKey || this.ids;
      this.$modal
        .confirm(`是否确认删除编号为：${customerKeys}的【${row.customerHelp}】？`)
        .then(function () {
          that.loading = true;
          return delCustomerRepair(customerKeys);
        })
        .then(() => {
          that.loading = true;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .finally(() => {
          that.loading = false;
        });
    },
    handleDisplay(row) {
      this.dialogVisible = true
      this.order = row
    },
    // 调派单位选择变化
    changeUnit(value) {
      this.dispatchForm.customerPlayer = null
      // console.log(typeof value, value.length, value[value.length -1], '值变化') // this.$refs['unit'].getCheckedNodes(),
      if (value && value.length !== 0) {
        let deptId = value[value.length -1]
        FrimUser(deptId).then(res => {
          this.users = res.rows
          console.log(res, 'tttt')
        })
      }
    },
    // 调派提交
    onSubmitInfo() {
      this.$refs["displayRef"].validate((valid) => {
        console.log(this.dispatchForm, this.$route.params, '提交的数据')
        if (valid) {
          this.btnLoading = true;
          getUserProfile().then(response => {
            // this.user = response.data.user;
            // console.log(res, '223')
            let params = {
              loginmanId: response.data.user.userId,
              customerKey: this.order.customerKey,
              orderStatus: 1,
              customerPlayer: this.dispatchForm.customerPlayer.join(','),
              companyId: this.dispatchForm.companyId[this.dispatchForm.companyId.length - 1]
            }
            console.log(params)
            designate(params)
              .then((response) => {
                if (response.resultCode == 200 || response.code == 200) {
                  this.$modal.msgSuccess("调派成功");
                  this.dialogVisible = false
                } else {
                  this.$modal.msgError(`提交调派失败${response.resultCode || response.code}:${response.resultMsg || response.msg}`);
                }
                // getList();
              })
              .finally(() => {
                this.btnLoading = false;
              });
          });
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "web/CustomerRepair/export",
        {
          ...this.queryParams,
        },
        `CustomerRepair_${new Date().getTime()}.xlsx`
      );
    },
    // 处理部门数据
    treeData (source, id = 'deptId', parentId= 'parentId', children= 'children', rootId) {
      const newRootId = rootId || (source && source.length > 0 && source[0].parentId) || '100'
      console.log(newRootId, 'r4554545')
      if (source.length !== 0) {
        return source.filter((father) => {
          father.label = father.deptName
          father.value = father.deptId
          const parent = father
          // console.log(parent, parent[id], '数据库')
          // const branchArr = source.filter(child => parent[id] === child[parentId])// 返回每一项的子级数组
          const branchArr = source.filter(child => father.deptId == child.parentId)// 返回每一项的子级数组
          // console.log(branchArr, '哈哈哈')
          if (branchArr.length > 0) {

            parent[children] = branchArr
            // parent.children = branchArr
          } else {
            delete parent[children]
            // delete parent.children// 如果存在子级，则给父级添加一个children属性，并赋值
          }
          // return parent[parentId] === newRootId // 返回第一层
          return parent.parentId == newRootId // 返回第一层
        })
      }
    }

  }
}
</script>
